'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { 
  getAllTabTokens, 
  clearAllTabTokens, 
  cleanupExpiredTokens,
  getCacheInfo,
  hasUserCache
} from '@/lib/cache'

export default function TokenManagerPage() {
  const [tabTokens, setTabTokens] = useState<Array<{ tabId: string; token: string | null; isCurrent: boolean }>>([])
  const [cacheInfo, setCacheInfo] = useState<{ localStorage: number; sessionStorage: number }>({ localStorage: 0, sessionStorage: 0 })
  const [hasCache, setHasCache] = useState(false)
  const [lastUpdate, setLastUpdate] = useState<Date>(new Date())

  useEffect(() => {
    updateTokenInfo()
    
    // 每10秒自动更新一次
    const interval = setInterval(updateTokenInfo, 10000)
    
    return () => clearInterval(interval)
  }, [])

  const updateTokenInfo = () => {
    setTabTokens(getAllTabTokens())
    setCacheInfo(getCacheInfo())
    setHasCache(hasUserCache())
    setLastUpdate(new Date())
  }

  const handleCleanupExpired = () => {
    cleanupExpiredTokens()
    updateTokenInfo()
  }

  const handleClearAllTokens = () => {
    if (confirm('确定要清理所有标签页的Token吗？这将导致所有用户需要重新登录。')) {
      clearAllTabTokens()
      updateTokenInfo()
    }
  }

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const getTokenStatus = (token: string | null) => {
    if (!token) return { status: 'empty', label: '空', variant: 'secondary' as const }
    if (token.length < 20) return { status: 'invalid', label: '无效', variant: 'destructive' as const }
    return { status: 'valid', label: '有效', variant: 'default' as const }
  }

  return (
    <div className="space-y-6 p-6">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">Token管理工具</h1>
        <div className="flex gap-2">
          <Button onClick={updateTokenInfo} variant="outline">
            🔄 刷新
          </Button>
          <Button onClick={handleCleanupExpired} variant="outline">
            🧹 清理过期
          </Button>
          <Button onClick={handleClearAllTokens} variant="destructive">
            🗑️ 清理所有
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">活跃标签页</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{tabTokens.length}</div>
            <p className="text-xs text-muted-foreground">当前活跃的标签页数量</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">缓存大小</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatBytes(cacheInfo.localStorage)}</div>
            <p className="text-xs text-muted-foreground">localStorage使用量</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm">最后更新</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-sm font-bold">{lastUpdate.toLocaleTimeString()}</div>
            <p className="text-xs text-muted-foreground">信息更新时间</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>标签页Token详情</CardTitle>
          <CardDescription>
            显示所有标签页的Token状态，包括当前标签页和活跃状态
          </CardDescription>
        </CardHeader>
        <CardContent>
          {tabTokens.length > 0 ? (
            <div className="space-y-3">
              {tabTokens.map((tabInfo, index) => {
                const tokenStatus = getTokenStatus(tabInfo.token)
                return (
                  <div 
                    key={index} 
                    className={`p-4 rounded-lg border ${
                      tabInfo.isCurrent ? 'border-blue-200 bg-blue-50' : 'border-gray-200'
                    }`}
                  >
                    <div className="flex justify-between items-start mb-3">
                      <div className="flex items-center gap-2">
                        <span className="font-mono text-sm">{tabInfo.tabId}</span>
                        {tabInfo.isCurrent && (
                          <Badge variant="default" className="text-xs">
                            当前标签页
                          </Badge>
                        )}
                        <Badge variant={tokenStatus.variant} className="text-xs">
                          {tokenStatus.label}
                        </Badge>
                      </div>
                      <div className="text-xs text-gray-500">
                        #{index + 1}
                      </div>
                    </div>
                    
                    <div className="space-y-2">
                      <div className="text-sm">
                        <span className="font-medium">Token:</span>
                        <span className="ml-2 font-mono text-xs break-all">
                          {tabInfo.token ? 
                            `${tabInfo.token.substring(0, 50)}...` : 
                            '无Token'
                          }
                        </span>
                      </div>
                      
                      <div className="text-xs text-gray-600">
                        <span>状态:</span>
                        <span className="ml-2">
                          {tabInfo.isCurrent ? '当前活跃' : '其他标签页'}
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <div className="text-lg mb-2">暂无标签页Token</div>
              <div className="text-sm">所有标签页都未登录或Token已清理</div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>缓存信息</CardTitle>
          <CardDescription>浏览器存储使用情况</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <h4 className="font-semibold">localStorage</h4>
              <div className="text-sm space-y-1">
                <div>大小: {formatBytes(cacheInfo.localStorage)}</div>
                <div>状态: {hasCache ? '有用户缓存' : '无用户缓存'}</div>
              </div>
            </div>
            
            <div className="space-y-2">
              <h4 className="font-semibold">sessionStorage</h4>
              <div className="text-sm space-y-1">
                <div>大小: {formatBytes(cacheInfo.sessionStorage)}</div>
                <div>状态: 标签页会话数据</div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>操作说明</CardTitle>
          <CardDescription>Token管理工具的使用说明</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <div className="space-y-2">
              <h4 className="font-semibold">功能说明:</h4>
              <ul className="list-disc list-inside space-y-1 ml-4 text-sm">
                <li><strong>刷新:</strong> 手动更新Token信息</li>
                <li><strong>清理过期:</strong> 自动清理已过期的Token（2小时无活动）</li>
                <li><strong>清理所有:</strong> 强制清理所有标签页的Token</li>
                <li><strong>自动更新:</strong> 每10秒自动刷新信息</li>
              </ul>
            </div>
            
            <div className="space-y-2">
              <h4 className="font-semibold">安全提醒:</h4>
              <ul className="list-disc list-inside space-y-1 ml-4 text-sm text-orange-600">
                <li>清理所有Token将导致所有用户需要重新登录</li>
                <li>建议在维护期间或安全事件后使用</li>
                <li>定期使用"清理过期"功能维护系统</li>
              </ul>
            </div>
            
            <div className="space-y-2">
              <h4 className="font-semibold">监控建议:</h4>
              <ul className="list-disc list-inside space-y-1 ml-4 text-sm text-blue-600">
                <li>定期检查活跃标签页数量</li>
                <li>监控缓存大小变化</li>
                <li>关注异常Token状态</li>
              </ul>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
